/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AdminRegRolTrab1.java
 *
 * Created on 14-ago-2009, 11:27:20
 */

package com.jomijushi.fid.interfaz;

import com.jomijushi.fid.dominio.FidRolTrabajador;
import com.jomijushi.fid.servicios.RolTrabajadorImplementsService;
import com.jomijushi.fid.servicios.RolTrabajadorInterfazService;
import java.util.List;


import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author miguel
 */
public class AdminRegRolTrab extends javax.swing.JDialog {

    private int idSeleccionado=-1;
    


    /** Creates new form AdminRegRolTrab1 */
    public AdminRegRolTrab(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(this);
        CargarTabla();  // Carga los Datos que Existan en la Tabla de Entrada    
    }

    public void CargarTabla()
    {
        // Aqui definimos ¿Qué columnas? seran editables
        // true -> Editable; false -> No Editable
        
        RolTrabajadorInterfazService frlservice = new RolTrabajadorImplementsService();
        frlservice.setEntityManagerFactory(PanelPrincipal.emf);
        List<FidRolTrabajador> lst = frlservice.Listar(false,"",true,0,0);
        //ya vienen ordenados alfabeticamente
        for(int i=0; i<lst.size(); i++)
            System.out.println("rol trabajador = "+lst.get(i).getNombre());
        
        FidRolTrabajador frt;        
        //List<FidRolTrabajador> lst = LRT;
        int cant= lst.size();

        ModeloTabla.canEdit = new boolean [] {false, false, false};
        ModeloTabla modeloTabla= new ModeloTabla();
        
        if(cant>0){
            modeloTabla.addColumn("ID");
            modeloTabla.addColumn("Rol Trabajador");
            modeloTabla.addColumn("Descripción");

            for ( int i=0; i<cant; i++){
                frt = new FidRolTrabajador();
                Object[] fila = new Object[3];
                frt = lst.get(i);
                fila[0] = frt.getId();
                fila[1] = frt.getNombre();
                fila[2] = frt.getDescripcion();

                modeloTabla.addRow(fila);
            }
        }
        else
        {
            Object[] obj={null,null,null,null};
            modeloTabla.addColumn("ID");
            modeloTabla.addColumn("Rol Trabajador");
            modeloTabla.addColumn("Descripción", obj);            
        }
        Tabla.setModel(modeloTabla);
        // Seccion para Configurar Visualizacion de Tabla
        TableColumnModel tcm = Tabla.getColumnModel();
        // Se pide la columna por su número, empezando en cero.
        //TableColumn columnaABorrar = tcm.getColumn(0);
        Tabla.removeColumn (tcm.getColumn(0));  // oculta columna de tabla
        tcm.getColumn(1).setPreferredWidth(100);
    }

    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        rol = new javax.swing.JTextField();
        BotonAgregar = new javax.swing.JButton();
        BotonEditar = new javax.swing.JButton();
        BotonRemover = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        Tabla = new javax.swing.JTable();
        BotonCancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane2 = new javax.swing.JScrollPane();
        descripcion = new javax.swing.JTextArea();
        BotonActualizar = new javax.swing.JButton();
        BotonLimpiar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Registrar Rol Trabajador");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jLabel1.setText("Ingrese Rol:");

        rol.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                rolKeyTyped(evt);
            }
        });

        BotonAgregar.setIcon(new ImageIcon(getClass().getResource("/Images/add_16.png")));
        BotonAgregar.setText("Agregar");
        BotonAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonAgregarActionPerformed(evt);
            }
        });

        BotonEditar.setIcon(new ImageIcon(getClass().getResource("/Images/pencil.png")));
        BotonEditar.setText("Editar");
        BotonEditar.setEnabled(false);
        BotonEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonEditarActionPerformed(evt);
            }
        });

        BotonRemover.setIcon(new ImageIcon(getClass().getResource("/Images/delete.png")));
        BotonRemover.setText("Remover");
        BotonRemover.setEnabled(false);
        BotonRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonRemoverActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        Tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"", "", null},
                {null, "", null},
                {null, "", null},
                {null, "", null}
            },
            new String [] {
                "ID", "Rol Trabajador", "Descripción"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        Tabla.setVerifyInputWhenFocusTarget(false);
        Tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TablaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(Tabla);
        Tabla.getColumnModel().getColumn(0).setResizable(false);
        Tabla.getColumnModel().getColumn(0).setPreferredWidth(0);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 143, Short.MAX_VALUE)
        );

        BotonCancelar.setIcon(new ImageIcon(getClass().getResource("/Images/cancel.png")));
        BotonCancelar.setText("Cancelar");
        BotonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonCancelarActionPerformed(evt);
            }
        });

        jLabel2.setText("Desacripción:");

        jSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);

        descripcion.setColumns(20);
        descripcion.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
        descripcion.setLineWrap(true);
        descripcion.setRows(5);
        descripcion.setWrapStyleWord(true);
        jScrollPane2.setViewportView(descripcion);

        BotonActualizar.setIcon(new ImageIcon(getClass().getResource("/Images/arrow_refresh.png")));
        BotonActualizar.setText("Actualizar");
        BotonActualizar.setEnabled(false);
        BotonActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonActualizarActionPerformed(evt);
            }
        });

        BotonLimpiar.setText("Limpiar");
        BotonLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotonLimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rol, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                        .addGap(1, 1, 1)))
                .addGap(9, 9, 9)
                .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 1, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(BotonAgregar, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                    .addComponent(BotonEditar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                    .addComponent(BotonActualizar, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                    .addComponent(BotonRemover, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                    .addComponent(BotonCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                    .addComponent(BotonLimpiar, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(134, 134, 134))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel1)
                                .addComponent(rol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(BotonAgregar))
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(BotonLimpiar)
                                .addGap(53, 53, 53)
                                .addComponent(BotonEditar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                                .addComponent(BotonActualizar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BotonRemover)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BotonCancelar)
                                .addGap(40, 40, 40)))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BotonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonAgregarActionPerformed
       
        if(rol.getText().length() > 0){
            FidRolTrabajador roltrabajador = new FidRolTrabajador();
            roltrabajador.setNombre(rol.getText());
            roltrabajador.setDescripcion(descripcion.getText());
            RolTrabajadorImplementsService rtservice = new RolTrabajadorImplementsService();
            rtservice.setEntityManagerFactory(PanelPrincipal.emf);
            rtservice.crearRolTrabajador(roltrabajador);
            //JOptionPane.showMessageDialog(this, "Rol Guardado Correctamente", "Rol Trabajador", JOptionPane.INFORMATION_MESSAGE);
            CargarTabla();
            Limpiar();
        }
        else{
            JOptionPane.showMessageDialog(this, "Debe Ingresar un Rol como mínimo.", "Rol Trabajador", JOptionPane.WARNING_MESSAGE);
        }
        BotonEditar.setEnabled(false);
    }//GEN-LAST:event_BotonAgregarActionPerformed

    private void BotonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonCancelarActionPerformed
        
        this.setVisible(false);
    }//GEN-LAST:event_BotonCancelarActionPerformed

    private void BotonEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonEditarActionPerformed

        // Obtenemos los datos de la fila seleccionada
        String codigo = Tabla.getModel().getValueAt(Tabla.getSelectedRow(),0).toString();
        System.out.println("Contenido de Codigo: "+ codigo);
        
        idSeleccionado = Integer.parseInt(codigo);
        rol.setText(Tabla.getModel().getValueAt(Tabla.getSelectedRow(),1).toString());
        descripcion.setText(Tabla.getModel().getValueAt(Tabla.getSelectedRow(),2).toString());

        // Botones
        BotonAgregar.setEnabled(false);
        BotonEditar.setEnabled(false);
        BotonActualizar.setEnabled(true);
        BotonRemover.setEnabled(true);
    }//GEN-LAST:event_BotonEditarActionPerformed

    private void BotonActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonActualizarActionPerformed

        RolTrabajadorInterfazService rtservice = new RolTrabajadorImplementsService();
        rtservice.setEntityManagerFactory(PanelPrincipal.emf);
        
        FidRolTrabajador rolTrabajador = rtservice.buscarRolTrabajador(idSeleccionado);

        //editaremos los datos que deseemos
        //se supone que el id no, por que sera el mismo rol, no uno nuevo
        rolTrabajador.setDescripcion(descripcion.getText());
        rolTrabajador.setNombre(rol.getText());
        
        rtservice.editarRolTrabajador(rolTrabajador);
        //JOptionPane.showMessageDialog(this, "Rol Actualizado", "Rol Trabajador", JOptionPane.INFORMATION_MESSAGE);
        CargarTabla();

        BotonAgregar.setEnabled(true);
        BotonEditar.setEnabled(false);
        BotonActualizar.setEnabled(false);
        BotonRemover.setEnabled(false);

        Limpiar();
    }//GEN-LAST:event_BotonActualizarActionPerformed

    private void TablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TablaMouseClicked
        
        BotonEditar.setEnabled(true);        
    }//GEN-LAST:event_TablaMouseClicked

    private void BotonRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonRemoverActionPerformed

        //borraremos el rol
        RolTrabajadorInterfazService rtservice = new RolTrabajadorImplementsService();
        rtservice.setEntityManagerFactory(PanelPrincipal.emf);
        rtservice.eliminarRolTrabajador(idSeleccionado);
        CargarTabla();
        BotonAgregar.setEnabled(true);
        BotonEditar.setEnabled(false);
        BotonActualizar.setEnabled(false);
        BotonRemover.setEnabled(false);

        Limpiar();
    }//GEN-LAST:event_BotonRemoverActionPerformed

    private void BotonLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonLimpiarActionPerformed
        // TODO add your handling code here:
        Limpiar();
        CargarTabla();
        BotonAgregar.setEnabled(true);
        BotonEditar.setEnabled(false);
        BotonActualizar.setEnabled(false);
        BotonRemover.setEnabled(false);

    }//GEN-LAST:event_BotonLimpiarActionPerformed

    private void rolKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_rolKeyTyped
        // TODO add your handling code here:
        SoloTexto(evt);
    }//GEN-LAST:event_rolKeyTyped

    private void SoloTexto(java.awt.event.KeyEvent evt)
    {
        char c=evt.getKeyChar();
        if(Character.isDigit(c))
            evt.consume();
    }
    
    private void Limpiar()
    {
        rol.setText("");
        descripcion.setText("");
        idSeleccionado=-1;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                AdminRegRolTrab dialog = new AdminRegRolTrab(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotonActualizar;
    private javax.swing.JButton BotonAgregar;
    private javax.swing.JButton BotonCancelar;
    private javax.swing.JButton BotonEditar;
    private javax.swing.JButton BotonLimpiar;
    private javax.swing.JButton BotonRemover;
    private javax.swing.JTable Tabla;
    private javax.swing.JTextArea descripcion;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField rol;
    // End of variables declaration//GEN-END:variables

}
